//
//  SZCountryCityController.m
//  test8
//
//  Created by lanou on 16/1/14.
//  Copyright © 2016年 HuangZuCui. All rights reserved.
//

#import "SZCountryCityController.h"
#import "PKRequestManager.h"
#import "SZBaiDuMapViewController.h"
#import <FMDB.h>

// 各地城市列表
#define kCityURL @"http://morguo.com/community.php?mod=search&cityall=1&androidflag=1&appfrom=ios&iosversion=3.13"

@interface SZCountryCityController () <UISearchResultsUpdating, UISearchBarDelegate>
/** 热门城市 */
@property (nonatomic, strong) NSMutableArray *hotCityArray;
/** 城市首字母排序 */
@property (nonatomic, strong) NSMutableArray *sortFirstArray;
/** 城市列表数据源字典 */
@property (nonatomic, strong) NSMutableDictionary *dataSource;
/** 所有城市 */
@property (nonatomic, strong) NSMutableArray *dataArray;
/** 搜索结果数组 */
@property (nonatomic, retain) NSMutableArray *resultArray;
/** 搜索控制器 */
@property (nonatomic, strong) UISearchController *searchController;

@property (nonatomic, strong) FMDatabase *db;
@end

@implementation SZCountryCityController

/**
 *  懒加载
 */
- (NSMutableDictionary *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableDictionary dictionary];
    }
    return _dataSource;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _resultArray = [NSMutableArray array];
    _sortFirstArray = [NSMutableArray array];
    _hotCityArray = [NSMutableArray array];
    _dataArray = [NSMutableArray array];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CityTableViewCell"];
    
    NSString *cache = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"KaiJingFMDB.db"];
    
    _db = [FMDatabase databaseWithPath:cache];
    if ([_db open]) {
        SZLog(@"打开数据库成功");
    } else {
        SZLog(@"打开数据库失败");
    }
    
    [_db executeUpdate:@"CREATE TABLE KJCountryCityList (array BLOB)"];
    
    
    NSData *data = [_db dataForQuery:@"SELECT array FROM KJCountryCityList"];
    if (data) {
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        [self parseDictionary:dataDic];
        [self.tableView reloadData];
    } else {
        [self setupData];
    }
    [self addSearchBar];
}

/**
 *  添加搜索
 */
- (void)addSearchBar {
    
    //初始化 UISearchController
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    
    // 设置代理
    self.searchController.searchResultsUpdater = self;
    
    //搜索时背景变模糊
//    self.searchController.obscuresBackgroundDuringPresentation = YES;
    self.searchController.hidesNavigationBarDuringPresentation = YES;
    
    // 设置searchBar位置自适应
    [self.searchController.searchBar sizeToFit];
    
    self.searchController.searchBar.delegate = self;
    self.searchController.searchBar.showsSearchResultsButton = YES;
    
    _searchController.dimsBackgroundDuringPresentation = NO;
    
    //设置 searchBar 为 tableView 的表头
    self.tableView.tableHeaderView = self.searchController.searchBar;
}

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    // 获取搜索框内输入的内容
    NSString *searchString = self.searchController.searchBar.text;
    
    // NSPredicate用于查询(对NSArray进行过滤, 判断字符串首字符是否为字母, 字符串替换, 截取字符串, 判断手机号码，电话号码函数, 邮箱验证、电话号码验证, NSDate进行筛选)
    
    NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchString];
    
    if (self.resultArray != nil) {
        [self.resultArray removeAllObjects];
    }
    
    // filteredArrayUsingPredicate  通过给定条件来进行过滤，过滤后形成一个新的数组
    
    self.resultArray = [NSMutableArray arrayWithArray:[self.dataArray filteredArrayUsingPredicate:preicate]];
    
    [self.tableView reloadData];
}

- (void)parseDictionary:(NSDictionary *)dic {
    NSArray *citylist = dic[@"data"][@"citylist"];
    for (NSDictionary *city in citylist) {
        NSString *key = city[@"name"];
        NSArray *values = city[@"city"];
        NSMutableArray *tempArray = [NSMutableArray array];
        for (NSDictionary *subCity in values) {
            [tempArray addObject:subCity[@"name"]];
            [_dataArray addObject:subCity[@"name"]];
        }
        [self.dataSource setObject:tempArray forKey:key];
        [_sortFirstArray addObject:key];
    }
    // 数组排序
    [_sortFirstArray sortUsingSelector:@selector(compare:)];
}


/**
 *  解析各地城市数据
 */
- (void)setupData {
    // 解析城市列表
    [PKRequestManager requestWithUrlString:kCityURL parDic:nil method:GET finish:^(NSDictionary *dataDic) {
        
        [self parseDictionary:dataDic];
        NSData *data = [NSJSONSerialization dataWithJSONObject:dataDic options:NSJSONWritingPrettyPrinted error:nil];
        [_db executeUpdate:@"INSERT INTO KJCountryCityList (array) VALUES (?)",data];
        
        [self.tableView reloadData];
    } error:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.searchController.active) {
        return 1;
    } else {
        return _sortFirstArray.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.searchController.active) {
        return _resultArray.count;
    } else {
        NSArray *values = _dataSource[_sortFirstArray[section]];
        return values.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CityTableViewCell" forIndexPath:indexPath];
    if (self.searchController.active) {
        cell.textLabel.text = _resultArray[indexPath.row];
    } else {
        NSArray *values = _dataSource[_sortFirstArray[indexPath.section]];
        cell.textLabel.text = values[indexPath.row];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.searchController.active) {
        // 获取搜索结果中的元素必须在前
        NSString *city = _resultArray[indexPath.row];
        self.searchController.active = NO;
        SZBaiDuMapViewController *mapVC = [[SZBaiDuMapViewController alloc] init];
        mapVC.cityName = city;
        [self.navigationController pushViewController:mapVC animated:YES];
    } else {
        self.searchController.active = NO;
        NSString *key = _sortFirstArray[indexPath.section];
        NSArray *values = _dataSource[key];
        NSString *city = values[indexPath.row];
        SZBaiDuMapViewController *mapVC = [[SZBaiDuMapViewController alloc] init];
        mapVC.cityName = city;
        [self.navigationController pushViewController:mapVC animated:YES];
    }
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return _sortFirstArray;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (self.searchController.active) {
        return nil;
    } else {
        return _sortFirstArray[section];
    }
}
@end
